import { LoginType } from '@app/types/enums';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

import { AccessTokenDto } from './dto/accesstoken.dto';
import { AccountLoginDto, CodeLogin } from './dto/auth.dto';

/**
 * 通过.. 引入AccountService会报错误：
 * Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument Object at index [0] is available in the AuthModule context
 */
import { LoginAccountDto } from '..';
import { AccountService } from '../account/account.service';

@Injectable()
export class AuthService {
  constructor(
    private accountService: AccountService,
    private jwtService: JwtService,
  ) {}

  async signIn(params: AccountLoginDto | CodeLogin): Promise<AccessTokenDto> {
    const { type, ...param } = params;
    if (type === LoginType.Account) {
      return await this.loginByAccount(param as LoginAccountDto);
    }

    const payload = { sub: type, username: type };

    return {
      accesstoken: await this.jwtService.signAsync(payload),
      expiredIn: '',
    };
  }

  async loginByAccount(params: LoginAccountDto): Promise<AccessTokenDto> {
    const data = await this.accountService.findAll();
    return {
      accesstoken: params.password + params.username,
      expiredIn: '',
    };
  }

  async validateUser(username: string, pass: string): Promise<any> {
    const account = await this.accountService.findOneBy({ username });
    if (account && account.password === pass) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const { password, ...result } = account;
      return result;
    }
    return null;
  }
}
